<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\bookpack;


use app\common\model\book\Book;
use app\common\model\bookpack\Bookpack;
use app\common\logic\BaseLogic;
use app\common\model\bookpack\BookpackAssociation;
use app\common\model\bookpack\BookpackRecommend;
use app\common\model\promotion\PromotionLink;
use app\common\service\FileService;
use think\facade\Db;
use think\facade\Log;


/**
 * Bookpack逻辑
 * Class BookpackLogic
 * @package app\adminapi\logic
 */
class BookpackLogic extends BaseLogic
{

    /**
     * 添加书包
     *
     * @param array $params
     * @return bool|string
     */
    public static function add(array $params)
    {

        $book_arr = $params['book_arr'] ?? 0;
        if (count($book_arr) != 5) {

            return '请配置全部五个位置书包书籍';
        }

        /**
         * lb_arr
         * sj_arr
         * bk_arr
         * jp_arr
         * tj_arr
         */
        foreach ($book_arr as $key => $item) {
            switch ($key) {
                case 'lb_arr' :    // 轮播书包
                    if (!self::saveBookpack($params, $book_arr['lb_arr'])) {

                        return false;
                    }
                    break;
                case 'sj_arr' :    // 书架书包
                    if (!self::saveBookpack($params, $book_arr['sj_arr'])) {

                        return false;
                    }
                    break;
                case 'bk_arr' :    // 爆款书包
                    if (!self::saveBookpack($params, $book_arr['bk_arr'])) {

                        return false;
                    }
                    break;
                case 'jp_arr' :    // 精品书包
                    if (!self::saveBookpack($params, $book_arr['jp_arr'])) {

                        return false;
                    }
                    break;
                case 'tj_arr' :    // 弹窗推荐书包
                    if (!self::saveBookpack($params, $book_arr['tj_arr'])) {

                        return false;
                    }
                    break;
            }
        }

        return true;
    }


    /**
     * 更新书包数据
     *
     * @param $params
     * @param $packArr
     * @return boolean
     */
    public static function saveBookpack($params, $packArr)
    {
        Db::startTrans();
        try {
            $platform      = $params['platform'] ?? 0;
            $name          = $params['name'] ?? '';
            $bookpack_type = $params['bookpack_type'] ?? 0;
            $admin_id      = $params['admin_id'];
            $position      = $packArr['position'] ?? 0;
            $book_arr      = $packArr['book_ids'] ?? [];

            if (!$platform || !$name || !$bookpack_type) {

                throw new \Exception('缺少参数');
            }
            $bp = Bookpack::where('platform', $platform)->where('bookpack_type', $bookpack_type)->where('position', $position)->findOrEmpty();
            if (!$bp) {
                $bp = new Bookpack();
            }
            $bp->platform      = $platform;
            $bp->name          = $name;
            $bp->admin_id      = $admin_id;
            $bp->position      = $position;
            $bp->bookpack_type = $bookpack_type;
            $bp->status        = 1;
            if (count($book_arr) != 0) {
                $bp->num = count($book_arr);
            }
            if (!$bp->save()) {

                throw new \Exception('书包更新失败');
            }
            // 先清空之前书包书籍内容，再重新更新
            if (!empty($book_arr)) {
                BookpackAssociation::where('bookpack_id', $bp->id)->delete();
                $arr  = [];
                $sort = 1;
                foreach ($book_arr as $item) {
                    $arr[] = [
                        'book_id'     => $item,
                        'bookpack_id' => $bp->id,
                        'sort'        => $sort,
                        'create_time' => time(),
                        'update_time' => time()
                    ];
                    $sort++;
                }
                BookpackAssociation::insertAll($arr);
            }
            Db::commit();

            return true;
        } catch (\Exception $exception) {
            Log::error('添加书包失败：' . $exception->getMessage() . '应用ID：' . $platform);
            Db::rollback();

            return false;
        }
    }


    /**
     * 添加书包书籍
     *
     * @param array $params
     * @return bool
     */
    public static function addBook(array $params): bool
    {
        $id       = $params['id'] ?? 0;
        $book_ids = $params['book_ids'] ?? [];
        if (!$id || !$book_ids) {

            return false;
        }
        Bookpack::where('id', $id)->update(['num' => count($book_ids)]);

        // 先清空之前书包书籍内容，再重新更新
        BookpackAssociation::where('bookpack_id', $id)->delete();
        foreach ($book_ids as $item) {
            BookpackAssociation::create([
                'book_id'     => $item,
                'bookpack_id' => $id,
                'sort'        => 0
            ]);
        }

        return true;
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/11 19:06
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            Bookpack::where('id', $params['id'])->update([
                'name'          => $params['name'],
                'position'      => $params['position'],
                'bookpack_type' => $params['bookpack_type'],
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * 删除书包
     *
     * @param $id
     * @return bool
     */
    public static function delete($platform, $id): bool
    {
        // 是否已经在在跑的推广链使用
        $link = PromotionLink::where('platform', $platform)
            ->where('bookpack_type', '<>', 0)
            ->where('status', 1)
            ->findOrEmpty();
        if (!$link->isEmpty()) {

            return '当前书包已经在推广链使用，请不要删除';
        }

        Db::startTrans();
        try {
            Bookpack::destroy($id);
            BookpackAssociation::where('bookpack_id', $id)->delete();
            BookpackRecommend::where('bookpack_id', $id)->delete();
            Db::commit();

            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());

            return false;
        }
    }


    /**
     * 获取书包详情
     *
     * @param $params
     * @return array
     */
    public static function detail($params): array
    {
        return Bookpack::findOrEmpty($params['id'])->toArray();
    }


    /**
     * 更改书包状态
     *
     * @param array $params
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public static function updateStatus(array $params)
    {
        $bookpack = Bookpack::where('id', $params['id'])->findOrEmpty();
        $where    = [];
        $where[]  = ['status', '=', 1];
        $where[]  = ['platform', '=', $bookpack->platform];
        $where[]  = ['position', '=', $bookpack->position];
        $where[]  = ['bookpack_type', '=', $bookpack->bookpack_type];
        if (Bookpack::where($where)->count() > 0) {
            self::setError('同一位置只能同时拥有一个上线书包');
            return false;
        }

        $bookpack->status = $params['status'] ?? 0;

        return $bookpack->save();
    }


    /**
     * 获取推荐弹窗书包列表
     *
     * @param int $platform
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getRecommendBook(array $params)
    {
        $bookpack = Bookpack::field('id,name')->where(['platform' => $params['platform'], 'position' => 5, 'bookpack_type' => $params['bookpack_type']])->findOrEmpty();
        $result   = [];
        if (!$bookpack->isEmpty()) {
            $bookidArr = BookpackAssociation::where('bookpack_id', $bookpack->id)->column('book_id');
            $result    = Book::where('id', 'in', $bookidArr)->field('id,book_name,intro,thumb')->select()->toArray();
            foreach ($result as &$item) {
                $item['thumb'] = FileService::getFileUrl($item['thumb']);
            }
        }
        return $result;
    }


    /**
     * 克隆书包
     *
     * @param $params
     * @return bool
     */
    public static function copyBookpack($params)
    {
        Db::startTrans();
        try {
            $platform     = $params['platform'] ?? 0;
            $copyPlatform = $params['copy_platform'] ?? 0;
            $bookpackType = $params['bookpack_type'] ?? 0;
            if (!$platform || !$copyPlatform) {

                throw new \Exception('缺少参数');
            }
            $copyQuery = Bookpack::where('platform', $copyPlatform);
            if ($bookpackType) {
                $copyQuery->where('bookpack_type', $bookpackType);
            }
            $copyBookpack = $copyQuery->select();
            if ($copyBookpack->isEmpty()) {

                throw new \Exception('复制书包不存在');
            }
            $time             = time();
            $copyBookpackData = [];
            $copyBookData     = [];
            foreach ($copyBookpack as $copyItem) {
                // 当前应用是否有该位置的书包，如果有则不变，没有则用复制的书包
                $bookpack  = Bookpack::where('position', $copyItem->position)
                    ->where('bookpack_type', $copyItem->bookpack_type)
                    ->where('platform', $platform)
                    ->findOrEmpty();
                $copyBook  = BookpackAssociation::where('bookpack_id', $copyItem->id)->select();
                $countBook = $copyBook->count();
                if ($bookpack->isEmpty()) {
                    $id = Bookpack::insertGetId([
                        'platform'      => $platform,
                        'admin_id'      => $params['admin_id'],
                        'name'          => $copyItem->name,
                        'position'      => $copyItem->position,
                        'bookpack_type' => $copyItem->bookpack_type,
                        'num'           => $copyItem->num,
                        'status'        => $copyItem->status,
                        'create_time'   => $time,
                        'update_time'   => $time
                    ]);

                    foreach ($copyBook as $copyBookItem) {
                        array_push($copyBookData, [
                            'book_id'     => $copyBookItem->book_id,
                            'bookpack_id' => $id,
                            'sort'        => $copyBookItem->sort,
                            'show_time'   => $copyBookItem->show_time,
                            'create_time' => $time,
                            'update_time' => $time
                        ]);
                    }

                    $bookpack      = Bookpack::where('id', '=', $id)->findOrEmpty();
                    $bookpack->num = $countBook;
                    $bookpack->save();
                } else {
                    foreach ($copyBook as $copyBookItem) {
                        array_push($copyBookData, [
                            'book_id'     => $copyBookItem->book_id,
                            'bookpack_id' => $bookpack->id,
                            'sort'        => $copyBookItem->sort,
                            'show_time'   => $copyBookItem->show_time,
                            'create_time' => $time,
                            'update_time' => $time
                        ]);
                    }
                    $bookpack->num = $countBook;
                    $bookpack->save();
                }
            }
            Bookpack::insertAll($copyBookpackData);

            // 克隆之前先清空该应用下对应的书包里的书籍
            $bookpackIds = Bookpack::where('platform', $platform)->column('id');
            BookpackAssociation::where('bookpack_id', 'in', $bookpackIds)->delete();
            BookpackAssociation::insertAll($copyBookData);

            Db::commit();

            return true;
        } catch (\Exception $exception) {
            Db::rollback();

            return false;
        }
    }
}
